/**
 * Markdown处理相关的组合式API
 * 负责Markdown内容渲染和DOM处理
 */
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';

export function useMarkdown() {
  // 初始化markdown解析器，延迟加载以提高性能
  let md: MarkdownIt | null = null;

  // 获取Markdown解析器实例
  function getMarkdownParser(): MarkdownIt {
    if (!md) {
      md = new MarkdownIt({
        html: true,
        linkify: true,
        typographer: true,
        highlight: function (str: string, lang: string): string {
          if (lang && hljs.getLanguage(lang)) {
            try {
              return '<pre class="hljs"><code>' + hljs.highlight(str, { language: lang }).value + '</code></pre>';
            } catch (__) {
              /* 忽略高亮错误 */
            }
          }
          return '<pre class="hljs"><code>' + md!.utils.escapeHtml(str) + '</code></pre>';
        }
      });
    }
    return md;
  }

  // 检测内容是否为Markdown格式
  function isMarkdownContent(content: string): boolean {
    const markdownPatterns = [
      /^#{1,6}\s+/m, // 标题
      /\[.+?\]\(.+?\)/, // 链接
      /\*\*.+?\*\*/, // 粗体
      /\*.+?\*/, // 斜体
      /```[\s\S]+?```/, // 代码块
      /^\s*[-*+]\s+/m, // 无序列表
      /^\s*\d+\.\s+/m, // 有序列表
      /!\[.+?\]\(.+?\)/, // 图片
    ];

    return markdownPatterns.some((pattern) => pattern.test(content));
  }

  // 渲染Markdown内容
  function renderMarkdown(content: string): string {
    if (isMarkdownContent(content)) {
      try {
        return getMarkdownParser().render(content);
      } catch (e) {
        console.error('Markdown渲染错误:', e);
        return content;
      }
    }
    return content;
  }

  // 处理DOM元素
  function processContentDOM(element: HTMLElement): void {
    // 处理表格样式
    const tables = element.querySelectorAll('table');
    tables.forEach((table) => {
      table.classList.add('md-table');
    });

    // 处理代码块
    const codeBlocks = element.querySelectorAll('pre code');
    codeBlocks.forEach((block) => {
      // 添加行号
      const lines = block.innerHTML.split('\n');
      let numberedLines = '';
      lines.forEach((line, index) => {
        numberedLines += `<div class="code-line"><span class="line-number">${index + 1}</span>${line}</div>`;
      });
      block.innerHTML = numberedLines;

      // 添加复制按钮
      const pre = block.parentElement;
      if (pre) {
        const copyButton = document.createElement('button');
        copyButton.className = 'copy-button';
        copyButton.innerHTML = '<i class="el-icon-document-copy"></i> 复制';
        copyButton.addEventListener('click', () => {
          const code = block.textContent || '';
          navigator.clipboard.writeText(code).then(() => {
            copyButton.innerHTML = '<i class="el-icon-check"></i> 已复制';
            setTimeout(() => {
              copyButton.innerHTML = '<i class="el-icon-document-copy"></i> 复制';
            }, 2000);
          });
        });
        pre.appendChild(copyButton);
      }
    });

    // 处理链接
    const links = element.querySelectorAll('a');
    links.forEach((link) => {
      link.setAttribute('target', '_blank');
      link.setAttribute('rel', 'noopener noreferrer');
    });

    // 处理图片
    const images = element.querySelectorAll('img:not(.emoji)');
    images.forEach((img) => {
      if (img instanceof HTMLImageElement) {
        // 添加图片懒加载
        img.loading = 'lazy';

        // 点击查看大图
        img.addEventListener('click', () => {
          const src = img.src;
          if (src) {
            const imagePreview = document.createElement('div');
            imagePreview.className = 'image-preview';
            imagePreview.innerHTML = `
							<div class="image-preview-backdrop"></div>
							<div class="image-preview-container">
								<img src="${src}" />
							</div>
						`;
            document.body.appendChild(imagePreview);

            imagePreview.addEventListener('click', () => {
              document.body.removeChild(imagePreview);
            });
          }
        });
        img.style.cursor = 'zoom-in';
      }
    });

    // 处理Emoji
    const emojis = element.querySelectorAll('img.emoji');
    emojis.forEach((emoji) => {
      if (emoji instanceof HTMLImageElement) {
        emoji.style.height = '1.2em';
        emoji.style.width = '1.2em';
        emoji.style.margin = '0 0.1em';
        emoji.style.verticalAlign = '-0.2em';
        emoji.style.display = 'inline';
        emoji.style.border = 'none';
        emoji.style.boxShadow = 'none';
      }
    });
  }

  return {
    renderMarkdown,
    processContentDOM,
    isMarkdownContent
  };
} 